package com.rp.data.tcp_ws.server_ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rp.common.utils.NullIs;
import com.rp.common.utils.SpringContextUtils;
import com.rp.configure.service.DeviceAttributeService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class ServerHandlerWs extends SimpleChannelInboundHandler<TextWebSocketFrame> {
//    @Autowired
//    CollectorFcService collectorFcService;
    /**
     * @Author HuJingYu
     * @Date 9:39 2021-01-11
     * @Description websocket返回值定义
     * key:
     *      alarmSize 报警长度推送
     *      deviceSize 主机在线长度推送
     *      alarm 报警推送
     *      map 地图数据推送
     */
    //public static Map<String,String> returnSocketMap = new HashMap<>();


    public static Map<Channel,String> channelUserMap = new HashMap<>();
    public static Map<Channel,String> channelSubjectMap = new HashMap<>();
    public static Map<Channel,String> channelSvgMap = new HashMap<>();
    private static DeviceAttributeService deviceAttributeService = (DeviceAttributeService) SpringContextUtils.getBean(DeviceAttributeService.class);

    public static String serverHandler16690OrgCode = "A02";
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接，通道开启！" + ctx.channel().remoteAddress());
        //添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup16690.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！" + ctx.channel().remoteAddress());
        //添加到channelGroup 通道组
        Collection<Channel> values = MyChannelHandlerPool.UserChannel.values();
        values.remove(ctx.channel());
        if (NullIs.isEmpty(channelSubjectMap.get(ctx.channel()))) {
            channelSubjectMap.remove(ctx.channel());
        }
        if (NullIs.isEmpty(channelUserMap.get(ctx.channel()))) {
            channelUserMap.remove(ctx.channel());
        }
        if (NullIs.isEmpty(channelSvgMap.get(ctx.channel()))) {
            channelSvgMap.remove(ctx.channel());
        }
        MyChannelHandlerPool.channelGroup16690.remove(ctx.channel());
    }
    //收到消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        JSONObject json= JSON.parseObject(msg.text());
        switch (json.get("type").toString()){
            case "subjectId":channelSubjectMap.put(ctx.channel(),json.get("id").toString());break;
            case "userId":channelUserMap.put(ctx.channel(),json.get("id").toString());break;
            case "svg":channelSvgMap.put(ctx.channel(),json.get("id").toString());
                ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(deviceAttributeService.getStateBySubject(json.get("id").toString())))) ;break;
            default:break;
        }
        MyChannelHandlerPool.UserChannel.put(msg.text(),ctx.channel());

//        collectorFcService.getCircuitValue(msg.text());
        if (msg.text().split(",")[0].equals("819d12d2ff0f52e5466227b211e6c705")){
        }


    }

    public static void sendAllMessage(Object socketViewModel) {
        //收到信息后，群发给所有channel
        for(Channel channel : MyChannelHandlerPool.channelGroup16690){
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(socketViewModel)));
        }
    }

}
